package com.zero.book.service;

import com.zero.book.message.MessageConstant;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

import static com.zero.book.message.MessageConstant.*;
import static com.zero.book.message.MessageConstant.SERIAL_LOAD_FAILURE;
import static com.zero.book.utils.PrintUtil.*;

public class SerialService {

    /**
     * 串行保存服务
     *
     * @param map 地图
     */
    public static <K, V> void serialSaveService(Map<K, V> map, MessageConstant...tips) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("books.txt"))) {
            oos.writeObject(map);
            oos.flush();
            if (tips.length > 0) {
                return;
            } else {
                print(SERIAL_SAVE_SUCCESS);
            }
            print(SERIAL_SAVE_SUCCESS);
        } catch (IOException e) {
            throw new RuntimeException(SERIAL_SAVE_FAILURE + "", e);
        }
    }

    /**
     * 串行加载服务
     *
     * @return {@link Map }<{@link K },{@link V }>
     */
    public static <K, V> Map<K, V> serialLoadService(MessageConstant... tips) {
//        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("books.txt")))
        try (ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(Paths.get("books.txt")))) {
            Map<K, V> ts = (Map<K, V>) ois.readObject();
            if (tips.length > 0) {
                return ts;
            } else {
                print(SERIAL_LOAD_SUCCESS);
            }
            return ts;
        } catch (ClassNotFoundException | IOException e) {
            // 输出异常详细信息，帮助定位问题
            throw new RuntimeException(SERIAL_LOAD_FAILURE + "", e);
        }
    }
}
